<?php
include '../includes/cPlayer.php';
include '../includes/cDatabase.php';
include '../includes/cPage.php';
include '../includes/cDates.php';

$cPage = new page("Create Ericsson Cup");
echo $cPage->getTitle();
echo $cPage->pageStringStart();
echo $cPage->contentStringStart();

$cDatabase = new database();

$connect = $cDatabase->connectToDatabase();
$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
$db = $cDatabase->selectDatabase($connect, $activeDatabase);

$selectArray[0] = '*';
$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, NULL, NULL, NULL, NULL);

$numMembers = mysqli_num_rows($result);
$numberRounds = CalculateNumberRounds($numMembers);
$numberByes = CalculateNumberByes($numMembers, $numberRounds);
echo "rounds ".$numberRounds." byes ".$numberByes;

$result = $cDatabase->DoesTableExist($connect, 'tandbergCup');
if ($result == FALSE)
{
	// Create this table
	$cDatabase->createTandbergCup($connect, $numberRounds);
	$numbers = range(0, ($numMembers-1));
	
	for ($count = 0; $count < ($numMembers); $count++)
	{
		//echo "<BR>count $count team ".$numbers[$count];
	}
	
	for ($shuffle = 0; $shuffle < 100; $shuffle++)
	{
		shuffle($numbers);
	}
	
	for ($count = 0; $count < ($numMembers); $count++)
	{
		//echo "<BR>count $count team ".$numbers[$count];
	}
	// Insert a bye for each team where relevant
	$notByeCount = 0;
	$byeCount = 0;
	for ($count = 0; $count <= ($numMembers+$numberByes); $count++)
	{
		if (($count%2==0) || ($byeCount >= $numberByes))	// It's even or we've run out of byes
		{
			$numbersWithByes[$count] = $numbers[$notByeCount];
			$notByeCount++;
		}
		else if ($byeCount < $numberByes)	// It's odd
		{
			$numbersWithByes[$count] = $numMembers+$byeCount;
			$byeCount++;
		}
	}
	
	$cDatabase->insertDraw($connect, $numbersWithByes, ($numMembers+$numberByes));
}
else
{
	echo "<BR>Table already exists";
}



function CalculateNumberRounds($numMembers)
{
	if ($numMembers > 64)
		return 7;
	else if ($numMembers > 32)
		return 6;
	else if ($numMembers > 16)
		return 5;
	else if ($numMembers > 8)
		return 4;
	else if ($numMembers > 4)
		return 3;
	else if ($numMembers > 2)
		return 2;
	else
		return 1;
}

function CalculateNumberByes($numMembers, $numberRounds)
{
	switch ($numberRounds)
	{
		case 7:
			return (128 - $numMembers);
			break;
		case 6:
			return (64 - $numMembers);
			break;
		case 5:
			return (32 - $numMembers);
			break;
		case 4:
			return (16 - $numMembers);
			break;
		case 3:
			return (8 - $numMembers);
			break;
		case 2:
			return (4 - $numMembers);
			break;
		case 1:
			return (2 - $numMembers);
			break;
		default:
			return 0;
			break;
	}
}
echo $cPage->getContentStringEnd();
echo $cPage->getMenu();
echo $cPage->getClear();
echo $cPage->pageStringEnd();
echo $cPage->getFooter();
?>